package com.alon.spring01.utils;

import com.alon.spring01.common.config.redis.RedissonManager;
import java.util.concurrent.TimeUnit;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: spring01
 * @description: redisson分布式锁
 * @author: yulongguang
 * @create: 2019-06-01 16:00
 **/
public class DistributedRedisLock {

    private static final Logger log = LoggerFactory.getLogger(DistributedRedisLock.class);

    /**
     * 从配置类中获取到redisson对象
     */
    private static Redisson redisson = RedissonManager.getRedisson();
    private static final String LOCK_TITLE = "redisLock_";

    /**
     * 加锁
     */
    public static boolean acquire(String lockName) {
        String key = LOCK_TITLE + lockName;
        RLock rLock = redisson.getLock(key);
        rLock.lock(2, TimeUnit.MINUTES);
        log.info("==========lock======{}", Thread.currentThread().getName());
        return true;
    }

    public static void release(String lockName) {
        //必须是和加锁时同一个key
        String key = LOCK_TITLE + lockName;
        RLock rlock = redisson.getLock(key);
        rlock.unlock();
        log.info("===========unlock=========={}", Thread.currentThread().getName());
    }
}
